<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>test page</title>
</head>
<body>
websocket测试<br>
<input id = "message" type="text">
<button onclick="sendMessage()">发送消息</button>
<button onclick="closeWebSocket()">关闭websocket连接</button>
<button onclick="logout()">退出登录</button>
<div id="context"></div>

<script src="http://libs.baidu.com/jquery/2.0.0/jquery.min.js"></script>
<script type="application/javascript">
    function logout() {
        closeWebSocket();
        $.ajax({
            url: "/logout",
            type: "POST",
            success: function (rsp) {
                console.log("退出登录成功")
                console.log(rsp)
            }
        })
    }

    var websocket = null;
    // 判断当前浏览榕是否支持 WebSocket
    if ('WebSocket' in window) {
        // 创建 WebSocket 对象，连接服务器端点
        websocket = new WebSocket("ws://localhost:8989/ws");
    } else {
        alert('Not support websocket')
    }
    // 连接发生错误的 回调方法
    websocket.onerror = function () {
        appendMessage("error");
    }
    // 连接成功建立的回调方法
    websocket.onopen = function (event) {
            appendMessage("open ");
        }
    // 接收到消息的回调方法
    websocket.onmessage = function (event) {
        appendMessage(event.data);
    }
    // 连接关闭的回调方法
    websocket.onclose = function () {
            appendMessage(" close ");
        }
    // 监听窗口关闭事件，当窗口关闭时，主动关闭 websocket 连接
    // 防止连接还没断开就关闭窗口，server 端会抛异常
    window.onbeforeunload = function () {
        websocket.close();
    }

    // 将消息显示在网页上
    function appendMessage(message) {
        var context = $("#context").html() + "<br/>" + message;
        $("#context").html(context);
    }

    // 关闭连接
    function closeWebSocket() {
        websocket.close();
        logout();
    }

    // 发送消息
    function sendMessage() {
        var message = $("#message").val();
        websocket.send(message);
    }
</script>

</body>
</html>